package com.ozo.cloud.common.feign;

import com.ozo.cloud.common.feign.interceptor.FeignRequestInterceptor;
import feign.RequestInterceptor;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * feign配置
 *
 * @author qiangesoft
 * @date 2024-11-21
 */
@Configuration
public class FeignConfiguration {

    @Bean(destroyMethod = "close")
    public CloseableHttpClient httpClient() {
        // 连接配置
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(400);
        connectionManager.setDefaultMaxPerRoute(100);

        // 请求配置
        RequestConfig requestConfig = RequestConfig.custom()
                // 从连接池获取连接等待超时时间
                .setConnectionRequestTimeout(2000)
                // 请求超时时间
                .setConnectTimeout(2000)
                // 等待服务响应超时时间
                .setSocketTimeout(15000)
                .build();

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create()
                .setConnectionManager(connectionManager)
                .setDefaultRequestConfig(requestConfig)
                .evictExpiredConnections();
        return httpClientBuilder.build();
    }

    @Bean
    @ConditionalOnMissingBean
    public RequestInterceptor requestInterceptor() {
        return new FeignRequestInterceptor();
    }

}
